export class UnitUtil {
  // 缓存每毫米的像素值
  private static cachedMmPx: number;
  // 缓存每 pt 的像素值
  private static cachedPtPx: number;
  /**
   *获取每毫米的像素值
   * @returns
   */
  static getOneMmsPx() {
    if (UnitUtil.cachedMmPx) {
      return UnitUtil.cachedMmPx;
    }

    const div = document.createElement('div');
    div.style.width = '1mm';
    document.body.appendChild(div);

    const { width } = div.getBoundingClientRect();
    const mm1 = Math.floor(width * 100) / 100; // 保留两位小数先向下取整
    div.remove();

    UnitUtil.cachedMmPx = mm1;
    return mm1;
  }
  /**
   * 获取每 pt 的像素值
   * @returns 获取每 pt 的像素值
   */
  static getOnePtPx = () => {
    if (UnitUtil.cachedPtPx) {
      return UnitUtil.cachedPtPx;
    }
    const div = document.createElement('div');
    div.style.width = '1pt';
    document.body.appendChild(div);

    const { width } = div.getBoundingClientRect();
    const pt1 = Math.floor(width * 100) / 100; // 保留两位小数先向下取整
    div.remove();
    UnitUtil.cachedPtPx = pt1;
    return pt1;
  };
  /**
   * 将 px 转换为 mm
   * @param px
   * @returns
   */
  static pxToMm(px: number) {
    const mmPerPx = 1 / UnitUtil.getOneMmsPx();
    return px * mmPerPx;
  }
  /**
   * 将 mm 转换为 px
   * @param mm
   * @returns
   */
  static mmToPx(mm: number) {
    return mm * UnitUtil.getOneMmsPx();
  }
  /**
   * 将 pt 转换为 px
   * @param pt
   * @returns
   */
  static ptToPx = (pt: number) => {
    const pxPerPt = UnitUtil.getOnePtPx();
    return pt * pxPerPt;
  };
  static pxToPt = (px: number) => {
    const pxPerPt = UnitUtil.getOnePtPx();
    return px / pxPerPt;
  };
  static getUnit() {
    return { pxPerPt: UnitUtil.getOnePtPx(), pxPerMm: UnitUtil.getOneMmsPx() };
  }
}
